<template>
  <div class="app-container bg-gray">
    <el-card class="box-1">
      <div slot="header">
        <span>上传视频</span>
      </div>
      <el-form ref="form" :model="form" :rules="formRules" label-width="160px">
        <!--<el-form-item label="分区：">
          <el-select v-model="form['catId']" placeholder="请选择所属分区" clearable>
            <el-option value="0" label="默认"/>
            <el-option v-for="item in catList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>-->
        <el-form-item label="标题：" prop="title">
          <el-input v-model="form.title" type="textarea" rows="4" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="视频：">
          <el-upload ref="upload" :http-request="upLoadTXVideo" :auto-upload="false" action=""
                     accept=".mp4,.ts,.flv,.wmv,.asf,.rm,.rmb,.mpg,.mpeg,.3gp,.mov,.webm,.mkv,.avi,.mp3,.m4a,.flac,.ogg,.wav"
                     drag>
            <i class="el-icon-upload"/>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
          <el-input v-model="form['mediaUrl']" readonly/>
        </el-form-item>
        <el-form-item label="封面：">
          <div class="remark">*注:不选择图片则默认选择视频第一帧作为封面</div>
          <ws-upload-single-img v-model="form['coverImgId']" :path="form['coverImgUrl']" width="320" height="180"/>
        </el-form-item>
        <el-form-item label="简介：">
          <el-input v-model="form.desc" type="textarea" rows="4"/>
        </el-form-item>
        <el-divider/>
        <el-form-item label="类型：">
          <el-radio-group v-model="form['type']">
            <el-radio label="1">普通</el-radio>
            <el-radio label="2">课程</el-radio>
          </el-radio-group>
        </el-form-item>
        <slot v-if="form['type']==='1'">
          <el-form-item label="播放列表：">
            <el-select v-model="form['classId']" placeholder="请选择播放列表">
              <el-option v-for="item in playClassList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="观看模式：">
            <el-radio-group v-model="form['payMode']" size="small">
              <el-radio label="0">免费</el-radio>
              <el-radio label="1">收费</el-radio>
              <el-radio label="2">会员</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form['payMode']==='1'" label="费用：">
            <el-input v-model="form['payMoney']" style="width: 240px;"/>
            <el-radio-group v-model="form['memberMode']" size="small">
              <el-radio label="0">会员免费</el-radio>
              <el-radio label="1">会员折扣</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form['payMode']!=='0'" label="试看：">
            <el-input-number v-model="form['tryTime']" placeholder="请输入可试看时长(/秒)"/>
          </el-form-item>
        </slot>
        <slot v-if="form['type']==='2'">
          <el-form-item label="所属课程：">
            <el-select v-model="form['courseId']" placeholder="请选择所属课程" clearable>
              <el-option v-for="item in courseList" :key="item.id" :label="item.name" :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item v-if="!form['isFree']" label="试看：">
            <el-input-number v-model="form['tryTime']" placeholder="请输入可试看时长(/秒)"/>
          </el-form-item>
        </slot>
        <el-divider/>
        <el-form-item v-if="!id" label="发表动态：">
          <el-input v-model="form['dynamicText']" type="textarea" rows="4" placeholder="选填"/>
        </el-form-item>
        <div style="text-align:center">
          <el-button type="primary" @click="submitForm('form')">保存</el-button>
          <el-button type="primary" @click="$router.back(-1)">取消</el-button>
        </div>
      </el-form>
    </el-card>
    <!--上传进度弹窗-->
    <el-dialog :visible.sync="videoUploadProgressVisible" :close-on-click-modal="false" :close-on-press-escape="false"
               :show-close="false" title="视频上传中..." width="360px">
      <el-progress :text-inside="true" :stroke-width="26" :percentage="parseFloat(videoUploadProgress)"/>
    </el-dialog>
  </div>
</template>

<script>
  import TcVod from 'vod-js-sdk-v6';

  export default {
    data() {
      return {
        // 页面标题
        title: '',

        catList: [],
        courseList: [],
        playClassList: [],

        form: {
          catId: '0',
          classId: '',
          title: '',
          type: '1',
          fileType: '',
          payMode: '0',
          memberMode: '0',
          tryTime: 0,
          dynamicText: '',
          mediaUrl: '',
          id: '',
          desc: '',
          isFree: true
        },
        formRules: {
          title: [{ required: true, message: '请输入标题', trigger: 'change' }]
        },
        // 视频上传弹窗
        videoUploadProgressVisible: false,
        // 视频上传进度
        videoUploadProgress: 0
      }
    },
    watch: {
      'form.courseId'(val) {
        for (let i = 0; i < this.courseList.length; i++) {
          if (val === this.courseList[i].id) {
            this.form['isFree'] = this.courseList[i].payMode === '0';
          }
        }
      }
    },
    created() {
      this.title = this.$route.query.title
      if (this.$route.query.id) {
        this.id = this.$route.query.id
        this.getData(this.$route.query.id)
      }
      this.getCourseList();
      this.getPlayClassList();
    },
    methods: {
      getData() {
        const url = '../videoAdmin/vodMedia/getMediaInfo'
        const data = {id: this.id}
        this.$store.dispatch('GetConnect', {url, data}).then(res => {
          this.form = res.data
        }).catch(e => {
          this.$message.error(e.msg + ',请刷新或联系管理员')
        })
      },
      // 获取所有可用的课程
      getCourseList() {
        const url = '../videoAdmin/course/getAllCourse';
        this.$store.dispatch('GetConnect', {url}).then(res => {
          this.courseList = res.data;
        }).catch(e => {
          this.$message.error(e.msg + ',请刷新或联系管理员')
        })
      },
      // 获取所有可用的课程
      getPlayClassList() {
        const url = '../videoAdmin/broadcaster/getAllPlayClass';
        this.$store.dispatch('GetConnect', {url}).then(res => {
          this.playClassList = res.data;
        }).catch(e => {
          this.$message.error(e.msg + ',请刷新或联系管理员')
        })
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            if (this.$refs.upload.uploadFiles.length > 0) {
              this.$refs.upload.submit();
            } else {
              this.doSubmit();
            }
          } else {
            this.$message.error('提交失败,请检查必填项')
          }
        })
      },
      doSubmit() {
        const data = Object.assign({}, this.form);
        data.operateType = this.id ? 'update' : 'add';
        const url = '../videoAdmin/broadcaster/uploadMedia';
        this.$store.dispatch('GetConnect', {url, data}).then(res => {
          this.$message.success(res.msg)
          this.$router.back(-1)
        }).catch((err) => {
          this.$message.error(err.msg)
        })
      },
      resetForm(formName) {
        this.$refs[formName].resetFields()
      },
      // 获取上传签名的函数
      getSignature() {
        const url = '../videoAdmin/getSign';
        return this.$store.dispatch('GetConnect', {url}).then(res => {
          return res.data.sign
        }).catch((err) => {
          this.$message.error(err.msg)
          this.videoUploadProgressVisible = false;
        })
      },

      // 腾讯云点播上传视频
      async upLoadTXVideo(file) {
        const that = this;
        this.videoUploadProgressVisible = true;
        const tcVod = new TcVod({
          getSignature: this.getSignature // 前文中所述的获取上传签名的函数
        })
        const uploader = tcVod.upload({
          mediaFile: file.file // 媒体文件（视频或音频或图片），类型为 File
        })
        uploader.on('media_progress', function (info) {
          that.videoUploadProgress = (info.percent * 100).toFixed(2) || 0;
          console.log(info.percent) // 进度
        })
        uploader.done().then(function (doneResult) {
          that.videoUploadProgressVisible = false;
          that.videoUploadProgress = 0;
          that.form.id = doneResult.fileId;
          that.form.mediaUrl = doneResult.video.url;
          that.form.fileType = file.file.type;
          that.$message.success('视频上传成功~');
          that.doSubmit();
        }).catch(function (err) {
          console.log(err);
          this.$message.error(err);
        })
      }
    }
  }
</script>

<style lang="scss" type="text/scss" scoped>
  @import '../../../../styles/index.scss';

  .box-1 {
    max-width: 1000px;
    margin: 0 auto;

    .el-form {
      max-width: 900px;

      .title {
        font-weight: 600;
      }

      .remark {
        font-size: 13px;
        color: $textGray;
      }

      > div > .el-button {
        @extend .bg-green;
        width: 20%;
        min-width: 160px;
      }
    }
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
